import { useCallback } from "react";
import { useSelector, useDispatch } from 'react-redux';
import Creator from "../store/actions";
import Creators from '../store/actions';
// 引入学生管理api
import UsersApi from "../api/user"

export const useUsers = () => {

    const dispatch = useDispatch();
    // 操作状态的行为
    const login = useCallback(async ({ username, password, phone }) => {
        const data = await UsersApi.login({ username, password, phone })
        dispatch(Creator.login(data));
    }, [dispatch]);

    const reg = useCallback(async ({ regname, regPWD1, regPWD2 }) => {
        const data = await UsersApi.reg({ regname, regPWD1, regPWD2 })
        dispatch(Creator.reg(data));
    }, [dispatch])
    return [{ reg, login }]
}
export const useUsersData = () => {
    const usersData = useSelector(state => state.usersData);
    const dispatch = useDispatch()
    const { curPage, eachPage } = usersData;
    const getUsers = useCallback(async () => {
        const data = await UsersApi.get({ curPage, eachPage })
        dispatch(Creators.getUsers(data))
    }, [curPage, eachPage, dispatch])
    // 获取当前页
    const setCurPage = useCallback(curPage => {
        dispatch(Creators.setCurPage({ curPage }))
    }, [dispatch])
    // 每页显示条数
    const setEachPage = useCallback(eachPage => {
        dispatch(Creators.setEachPage({ eachPage }))
    }, [dispatch])
    // 获取_id对应数据
    const findUsers = useCallback(async _id => {
        const data = await UsersApi.getOne({ _id })
        dispatch(Creator.findUsers({ data }))
    }, [dispatch])
    // 查询
    const findUserGet = useCallback(async username => {
        // 通过name去查询数据
        const data = await UsersApi.find(username)
        // 通过payload解构拿到data
        dispatch(Creators.findUserGet({ data }))
    }, [dispatch])
    return [usersData, { findUserGet, getUsers, setCurPage, setEachPage, findUsers }]
}



